#!/bin/bash


function show_usage(){
    printf "\n\nUsage:"
    printf "$0 options [parameters]\n"
    printf "\n"
    printf "Options:\n"
    printf "\n -s or --source-directory:\n Corsika 8 download directory, which contains the 'conanfile.py' recipe. Default is the current directory."
    printf "\n -d or --debug:\n Specify 'Debug' as build type for the installed dependences. This should be matched when building CORSIKA 8."
    printf "\n -r or --release:\n Specify 'Release' as build type for the installed dependences. This should be matched when building CORSIKA 8."
    printf "\n -rd or --release-with-debug:\n Specify 'RelWithDebInfo' as build type for the installed dependences. This should be matched when building CORSIKA 8."
    printf "\n\nExample: ./conan-install.sh --source-directory /some_path/corsika --debug"
    printf "\n -h or --help:\n Prints this message.\n"

exit 0
}

echo "|---------------------------------------------------|"
echo "|-----------------[ CORSIKA 8 ]---------------------|"
echo "|-----[ CONAN2 DEPENDENCIES INSTALL SCRIPT ]------- |"
echo "|---------------------------------------------------|"
echo "|-------------------- BEGIN ------------------------| "

echo " "

SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
  SOURCE=$(readlink "$SOURCE")
  [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )

BUILD_TYPE="RelWithDebInfo"
CORSIKA_DIR=${CURRENT_DIR}
CORSIKA_DIR_INFORMED=${CURRENT_DIR}
CONAN2_OUTPUT_FOLDER_NAME="conan_cmake"

printf "[ conan-install | info > This script is located at the directory: ${SCRIPT_DIR}\n"



if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]];then
    show_usage
fi

while [ ! -z "$1" ]; do
  case "$1" in
     --source-directory|-s)
         shift
         CORSIKA_DIR=$(readlink -e ${1})
         CORSIKA_DIR_INFORMED=${1}
         ;;
     --debug|-d)
         #shift
         BUILD_TYPE="Debug"
         ;;
     --release|-r)
         #shift
         BUILD_TYPE="Release"
         ;;
     --release-with-debug|-rd)
         #shift
         BUILD_TYPE="RelWithDebInfo"
         ;;
      --help|-h)
        #shift
         show_usage
         ;;
     *)
        show_usage
        ;;
  esac
if [ $# -gt 0 ]; then
shift
fi
done

if [[ ${#CORSIKA_DIR} -eq 0 ]]; then
  printf "[ conan-install | warning > Output folder for cmake scripts generated by conan2 not found.\n"
  printf "[ conan-install | warning > Directory '${CORSIKA_DIR_INFORMED}' does not exist.\n"
  exit 1
fi


if [ -d "${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME}" ]; then
  printf "[ conan-install | info > Output folder for cmake scripts generated by conan2 is: ${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME}\n"
else
  printf "[ conan-install | warning > Output folder for cmake scripts generated by conan2 not found.\n"
  printf "[ conan-install | warning > Creating directory  ${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME}.\n"
  mkdir -p "${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME}"
fi

if [ -f "${CORSIKA_DIR}/conanfile.py" ]; then
  printf "[ conan-install | info > conan2 recipe: ${CORSIKA_DIR}/conanfile.py\n"
else
  printf "[ conan-install | warning > conan2 recipe not found.\n"
  printf "[ conan-install | warning > File  '${CORSIKA_DIR}/conanfile.py' does not exist.\n"
  exit 1 
fi

# Conan2 variabes
CONAN2_HOME=$(readlink -e `conan config home`)
CONAN2_PROFILE_NAME="corsika8"
printf "[ conan-install | info > conan2 home: ${CONAN2_HOME}\n"

# Conan2 commands 
CONAN2_DEFAULT_PROFILE_COMMAND="conan profile detect --force"
CONAN2_PROFILE_COMMAND="conan profile detect --name ${CONAN2_PROFILE_NAME} --force"
CONAN2_INSTALL_COMMAND="conan install ${CORSIKA_DIR} --output-folder=${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME} --build=missing  --settings=build_type=${BUILD_TYPE} --profile=${CONAN2_PROFILE_NAME}"
CONAN2_SHOW_PROFLE_COMMAND="conan profile show -pr ${CONAN2_PROFILE_NAME}"

printf "[ conan-install | info > Creating default profile...\n\n"
eval $CONAN2_DEFAULT_PROFILE_COMMAND
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${CONAN2_DEFAULT_PROFILE_COMMAND}.\n"
	exit 126
fi	

printf "[ conan-install | info > Creating '${CONAN2_PROFILE_NAME}' profile...\n\n"
eval $CONAN2_PROFILE_COMMAND
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${CONAN2_PROFILE_COMMAND}.\n"
	exit 126
fi	

printf "\n\n[ conan-install | info > Editing '${CONAN2_PROFILE_NAME}' profile\n"

#========== cppstd setting ============
STD_NUMBER=`grep -n -m 1 "compiler.cppstd=" ${CONAN2_HOME}/profiles/${CONAN2_PROFILE_NAME} | cut -d: -f1`
SED_STD_COMMAND="sed -i '${STD_NUMBER}s/.*/compiler.cppstd=gnu17/' ${CONAN2_HOME}/profiles/${CONAN2_PROFILE_NAME}"

eval $SED_STD_COMMAND
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${SED_STD_COMMAND}\n"
	exit 126
fi	

#========== libcxx setting ============
CXX_NUMBER=`grep -n -m 1 "compiler.libcxx=" ${CONAN2_HOME}/profiles/${CONAN2_PROFILE_NAME} | cut -d: -f1`
SED_CXX_COMMAND="sed -i '${CXX_NUMBER}s/.*/compiler.libcxx=libstdc++11/' ${CONAN2_HOME}/profiles/${CONAN2_PROFILE_NAME}"

eval $SED_CXX_COMMAND
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${SED_CXX_COMMAND}\n"
	exit 126
fi	

eval $CONAN2_SHOW_PROFLE_COMMAND
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${CONAN2_SHOW_PROFLE_COMMAND}\n"
	exit 126
fi	

printf "[ conan-install | info > ${CONAN2_INSTALL_COMMAND}\n"

eval ${CONAN2_INSTALL_COMMAND}
if [ ! $? -eq 0 ]; then 
	printf "[ conan-install | error > Exit code 126 (Command invoked cannot execute):\n ${CONAN2_INSTALL_COMMAND}\n"
	exit 126
fi	

CORSIKA_CMAKE_SCRIPT="#!/bin/bash


function show_usage(){
    printf \"\n\nUsage:\"
    printf \"\$0 options [parameters]\n\"
    printf \"\n\"
    printf \"Options:\n\"
    printf \"\n -c or --cmake-flags:\n Additional flags and settings to cmake base command. Default is empty string.\"
    printf \"\n\nExample: ./corsika-cmake.sh --cmake-flags '-DUSE_Pythia8_C8=C8' \"
    printf \"\n\nNote: the source directory (the one containing CMakeLists.txt), CMAKE_BUILD_TYPE, CMAKE_POLICY_DEFAULT_CMP0091 and CMAKE_TOOLCHAIN_FILE are already set. Do not repeat them.\"
    printf \"\n -h or --help:\n Prints this message.\n\"

exit 0
}

echo \"|---------------------------------------------------|\"
echo \"|-----------------[ CORSIKA 8 ]---------------------|\"
echo \"|----------[ CMAKE CONFIGURATION SCRIPT ]---------- |\"
echo \"|---------------------------------------------------|\"
echo \"|-------------------- BEGIN ------------------------|\"

CMAKE_BASE_SETTINGS=\"cmake  -S ${CORSIKA_DIR} -D CONAN_CMAKE_DIR=${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME} -D CMAKE_TOOLCHAIN_FILE=${CORSIKA_DIR}/${CONAN2_OUTPUT_FOLDER_NAME}/conan_toolchain.cmake  -D CMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_BUILD_TYPE=${BUILD_TYPE}\"
CMAKE_ADDITIONAL_SETTINGS=\"\"

if [[ \"\$1\" == \"--help\" ]] || [[ \"\$1\" == \"-h\" ]];then
    show_usage
fi

while [ ! -z \"\$1\" ]; do
  case \"\$1\" in
     --cmake-flags|-c)
         shift
         CMAKE_ADDITIONAL_SETTINGS=\${1}
         ;;
      --help|-h)
        #shift
         show_usage
         ;;
     *)
        show_usage
        ;;
  esac
if [ \$# -gt 0 ]; then
shift
fi
done

printf \"[corsika-cmake | info >  Issuing CMake command :\n\"
printf '[corsika-cmake | info > \e[1;36m%s\e[0m\n\n\n' \"\${CMAKE_BASE_SETTINGS} \${CMAKE_ADDITIONAL_SETTINGS}\"

eval \"\${CMAKE_BASE_SETTINGS} \${CMAKE_ADDITIONAL_SETTINGS}\"

if [ ! \$? -eq 0 ]; then 
	printf \"[ corsika | error > Project configuration (CMake) failed. \n\"
	exit 1
fi

echo \"|---------------------------------------------------|\"
echo \"|-----------------[ CORSIKA 8 ]---------------------|\"
echo \"|----------[ CMAKE CONFIGURATION SCRIPT ]---------- |\"
echo \"|---------------------------------------------------|\"
echo \"|-------------------- END --------------------------|\"
"

printf "%s" "${CORSIKA_CMAKE_SCRIPT}" > ${SCRIPT_DIR}/corsika-cmake.sh
chmod +x ${SCRIPT_DIR}/corsika-cmake.sh

printf "\n\n[ conan-install | info > Copy and paste the commands below in the corsika-build directory:\n\n"
printf '\e[1;36m%s\e[0m\n' "> ${SCRIPT_DIR}/corsika-cmake.sh "
printf '\e[1;36m%s\e[0m\n' "> make -j8"

echo " "
echo "|---------------------------------------------------|"
echo "|-----------------[ CORSIKA 8 ]---------------------|"
echo "|-----[ CONAN2 DEPENDENCIES INSTALL SCRIPT ]------- |"
echo "|---------------------------------------------------|"
echo "|-------------------- END --------------------------| "
echo " "

exit 0
